<?php
/**
 *备货规则控制器
 *@author shipanpan
 */
class Backup_RuleController extends Controller_NeedLogin {

	/**
	 * 添加备货
	 */
	public function addAction() {
		$this->_rulePgaeCommon();
		$this->smarty->display('addBackupRule.tpl');
	}

	/**
	 * 编辑备货规则
	 * @return [type] [description]
	 */
	public function editAction() {
		$this->_rulePgaeCommon();
		$backupRuleId = $this->getRequest()->getQuery('ruleId');
		$backupRuleModel = new Backup_Model_BackupRule();
		$backupRule = $backupRuleModel->getDetail($backupRuleId);
		if (!$backupRule) {
			$this->showError('未找到待编辑的备货规则！');
		}

		//获取备货规则所属仓库的部门，在页面显示
		$backupRuleWarehouse = explode(',', $backupRule['warehouse']);
		$warehouseModel = new Application_Model_Warehouse();
		$warehouseDep = $warehouseModel->getWarehouseById($backupRuleWarehouse[0], ['id', 'dept_id']);
		if (!$warehouseDep) {
			$this->showError('未找到备货规则仓库所属部门！');
		}
		$backupRule['warehouseDep'] = $warehouseDep[0]['dept_id'];
		$departmentModel = new Application_Model_Department();
		$hasWarehouseDep = $departmentModel->hasWarehouse();

		//复原页面中的分类规则的选中状态，所以将'val1,val2'这个格式选项参数转换成数组
		$backupRuleFilterRule = $backupRule['filter_rule'];
		$backupRuleFilterRule = array_column($backupRuleFilterRule, null, 'filter_type');
		unset($backupRule['filter_rule']);
		foreach ($backupRuleFilterRule as $type => &$filterRule) {
			if ($filterRule['operator'] == 'eq') {
				$filterRule['operator_eq_params'] = explode(',', $filterRule['operator_eq_param']);
			}
		}

		$this->smarty->assign('backupRule', $backupRule);
		$this->smarty->assign('filterRule', $backupRuleFilterRule);
		$this->smarty->assign('hasWarehouseDep', $hasWarehouseDep);
		$this->smarty->display('editBackupRule.tpl');
	}

	/**
	 * 查看备货规则
	 * @return [type] [description]
	 */
	public function viewAction() {
		$backupRuleId = $this->getRequest()->getQuery('ruleId');
		$backupRuleModel = new Backup_Model_BackupRule();
		$backupRule = $backupRuleModel->getDetail($backupRuleId);
		if (!$backupRule) {
			$this->showError('未找到指定的备货规则！');
		}
		$this->_rulePgaeCommon();
		$backupRuleFilterRule = $backupRule['filter_rule'];
		$backupRuleFilterRule = array_column($backupRuleFilterRule, null, 'filter_type');
		unset($backupRule['filter_rule']);

		foreach ($backupRuleFilterRule as $type => &$filterRule) {
			if ($filterRule['operator'] == 'eq') {
				$filterRule['operator_eq_params'] = explode(',', $filterRule['operator_eq_param']);
			}
		}

		$warehouseModel = new Application_Model_Warehouse();
		$applyWarehouse = $warehouseModel->getWarehouseById($backupRule['warehouse'], ['id', 'warehouse_name']);
		$applyWarehouse = array_column($applyWarehouse, 'warehouse_name');
		$applyWarehouse = implode(',', $applyWarehouse);

		$this->smarty->assign('backupRule', $backupRule);
		$this->smarty->assign('filterRule', $backupRuleFilterRule);
		$this->smarty->assign('applyWarehouse', $applyWarehouse);
		$this->smarty->display('viewBackupRule.tpl');
	}

	/**
	 * 停用|启用备货规则
	 * @return [type] [description]
	 */
	public function onOffAction() {
		$backupRuleId = $this->getRequest()->getQuery('ruleId');
		$isOff = $this->getRequest()->getQuery('isOff');
		if (!in_array($isOff, [0, 1])) {
			json_encode(['status' => 'error', 'msg' => '请指定是启用规则还是停用规则！']);
			exit;
		}

		$backupRuleModel = new Backup_Model_BackupRule();
		$operator = $this->currentLoginUser('user_name');
		$success = $backupRuleModel->onOff($backupRuleId, $isOff, $operator);
		$action = $isOff == 1 ? "停用" : "启用";
		if ($success) {
			echo json_encode(['status' => 'success', 'msg' => $action . "成功！"]);
		} else {
			echo json_encode(['status' => 'error', 'msg' => $action . "失败！"]);
		}
	}

	public function turnOnAction() {
		$backupRuleId = $this->getRequest()->getQuery('ruleId');
		$startDate = $this->getRequest()->getQuery('startDate');
		$endDate = $this->getRequest()->getQuery('endDate');

		$backupRuleModel = new Backup_Model_BackupRule();
		//$startDate = '2016-06-21';
		//$endDate = '2016-06-23';
		$success = $backupRuleModel->turnOn($backupRuleId, $startDate, $endDate);

		if ($success) {
			echo json_encode(['status' => 'success', 'msg' => "启用成功！"]);
		} else {
			echo json_encode(['status' => 'error', 'msg' => "启用失败！"]);
		}
	}

	/**
	 * 停用备货规则
	 * @return [type] [description]
	 */
	public function turnOffAction() {
		$backupRuleId = $this->getRequest()->getQuery('ruleId');

		$backupRuleModel = new Backup_Model_BackupRule();
		$success = $backupRuleModel->turnOff($backupRuleId);

		if ($success) {
			echo json_encode(['status' => 'success', 'msg' => "停用成功！"]);
		} else {
			echo json_encode(['status' => 'error', 'msg' => "停用失败！"]);
		}
	}

	/**
	 * 备货规则页面共用部分
	 * @return [type] [description]
	 */
	private function _rulePgaeCommon() {
		$warehouseModel = new Application_Model_Warehouse();
		$allWarehouse = $warehouseModel->getAll(['id', 'warehouse_name']);
		$allWarehouse = array_column($allWarehouse, 'warehouse_name', 'id');

		$productGradeModel = new Application_Model_ProductGrade();
		$allProductGrade = $productGradeModel->getAllGrade(['id', 'name']);
		$this->smarty->assign('allWarehouse', $allWarehouse);
		$this->smarty->assign('allProductGrade', $allProductGrade);
	}

	/**
	 * 保存备货规则
	 * @return [type] [description]
	 */
	public function saveAction() {
		$backupRuleForm = $this->getRequest()->getParams();
		//去除空格，实体化特殊字符
		$backupRuleForm = array_map(function ($formFieldValue) {
			if (is_string($formFieldValue) && !is_numeric($formFieldValue)) {
				$formFieldValue = trim($formFieldValue);
				return htmlspecialchars($formFieldValue);
			}
			return $formFieldValue;
		}, $backupRuleForm);
		$needFormField = ['name', 'description', 'avg_sales_formula_type', 'min_backup', 'max_backup_base', 'max_backup_factor', 'backup_days_delivery_days_type', 'backup_days_shelves_days', 'backup_days_quality_testing_days', 'backup_days_need_backup_days', 'safe_stock_type', 'safe_stock_base', 'safe_stock_factor', 'safe_stock_shelves_days', 'safe_stock_quality_testing_days', 'safe_stock_need_backup_days', 'is_enable', 'priority', 'start_date', 'end_date', 'warehouse', 'warehouse_department'];

		$rule = [];
		//必要字段是否存在
		foreach ($needFormField as $field) {
			if (!isset($backupRuleForm[$field])) {
				$this->_helper->json(['status' => false, 'message' => "缺少字段:" . $field]);
			}
			$rule[$field] = $backupRuleForm[$field];
		}

		//如果安全库存是按天数计算，则检查是否设置交期时间的选择范围
		if ($backupRuleForm['safe_stock_type'] == 2) {
			if (!isset($backupRuleForm['safe_stock_delivery_days_type'])) {
				$this->_helper->json(['status' => false, 'message' => '安全库存按天计算需选择交期时间范围！']);
			}
			$rule['safe_stock_delivery_days_type'] = $backupRuleForm['safe_stock_delivery_days_type'];
		}

		if ($backupRuleForm['is_enable'] == 1) {
			list($startYear, $startMonth, $startDay) = explode('-', $backupRuleForm['start_date']);
			if (!checkdate($startMonth, $startDay, $startYear)) {
				$this->_helper->json(['status' => false, 'message' => '启用生效日期不合法！']);
			}
			list($endYear, $endMonth, $endDay) = explode('-', $backupRuleForm['end_date']);
			if (!checkdate($endMonth, $endDay, $endYear)) {
				$this->_helper->json(['status' => false, 'message' => "启用截止日期不合法！"]);
			}
		}

		$rule['warehouse'] = array_filter($rule['warehouse'], function ($warehouseId) {
			if ((int) $warehouseId > 0) {
				return true;
			}
			return false;
		});
		$rule['warehouse'] = implode(',', $rule['warehouse']);
		$now = date('Y-m-d H:i:s');
		$rule['modify_time'] = $now;
		$rule['modify_user'] = $this->currentLoginUser()['user_name'];
		$rule['is_delete'] = 0;

		$backupRuleModel = new Backup_Model_BackupRule();
		$sameNameRule = $backupRuleModel->getByName($backupRuleForm['name']);

		//更新
		if (isset($backupRuleForm['rule_id']) && (int) $backupRuleForm['rule_id'] > 0) {
			if ((count($sameNameRule) > 1) || (count($sameNameRule) == 1 && $sameNameRule[0]['id'] != $backupRuleForm['rule_id'])) {
				$this->_helper->json(['status' => false, 'message' => '已有同名称的备货规则，请选择其他名称！']);
			}
			$actionName = "保存";
			$rule['id'] = (int) $backupRuleForm['rule_id'];
			$ruleId = $rule['id'];

			$rule['modify_time'] = $now;
			$rule['modify_user'] = $this->currentLoginUser()['user_name'];
			//新增
		} else {
			if (count($sameNameRule)) {
				$this->_helper->json(['status' => false, 'message' => '已有同名称的备货规则，请选择其他名称！']);
			}
			$actionName = "新増";
			$rule['create_time'] = $now;
			$rule['creator'] = $this->currentLoginUser()['user_name'];

		}

		//备货规则的商品筛选规则
		$filterTypeArr = $backupRuleForm['rule_item_type'];
		$filterTypeOperator = $backupRuleForm['rule_item_type_operator'];
		$filterTypeOperatorMinParam = $backupRuleForm['rule_item_min_num'];
		$filterTypeOperatorMaxParam = $backupRuleForm['rule_item_max_num'];
		$filterTypeOperatorEqParam = $backupRuleForm['rule_item_operator_params'];
		$filterDescriptionArr = $backupRuleForm['rule_item_desc'];

		$filterRule = [];
		if (is_array($filterTypeArr) && count($filterTypeArr) > 0) {
			foreach ($filterTypeArr as $key => $type) {
				$backupGoodsFilterRule = [];
				$backupGoodsFilterRule['filter_type'] = htmlspecialchars($type);
				$backupGoodsFilterRule['operator'] = htmlspecialchars($filterTypeOperator[$key]);
				$backupGoodsFilterRule['operator_min_param'] = (float) $filterTypeOperatorMinParam[$key];
				$backupGoodsFilterRule['operator_max_param'] = (float) $filterTypeOperatorMaxParam[$key];
				$backupGoodsFilterRule['operator_eq_param'] = Helper_Security::removeXss($filterTypeOperatorEqParam[$key]);
				$backupGoodsFilterRule['description'] = Helper_Security::removeXss($filterDescriptionArr[$key]);
				$filterRule[] = $backupGoodsFilterRule;
			}
		}

		$saveRuleResult = $backupRuleModel->save($rule, $filterRule);
		if ($saveRuleResult) {
			$this->_helper->json(['status' => true, 'message' => '保存成功！']);
		} else {
			$this->_helper->json(['status' => false, 'message' => '保存失败，失败原因:' . $backupRuleModel->getErrorMsg()]);
		}
	}

	/**
	 * 备货规则列表
	 * @return [type] [description]
	 */
	public function listAction() {
		$queryParameter = $this->getRequest()->getQuery();
		$this->db = Model_Db::getInstance();
		$where = "";
		if (isset($queryParameter['start_date']) && $queryParameter['start_date']) {
			$where .= "AND " . $this->db->quoteInto(" start_date >=?", $queryParameter['start_date']) . " ";
		}

		if (isset($queryParameter['end_date']) && $queryParameter['end_date']) {
			$where .= "AND " . $this->db->quoteInto(" end_date <=?", $queryParameter['end_date']) . " ";
		}

		if (isset($queryParameter['is_enable']) && $queryParameter['is_enable']) {
			$where .= "AND " . $this->db->quoteInto(" is_enable =?", $queryParameter['is_enable']) . " ";
		}

		if (isset($queryParameter['priority']) && $queryParameter['priority']) {
			$where .= "AND " . $this->db->quoteInto(" priority =?", $queryParameter['priority']) . " ";
		}

		if (isset($queryParameter['warehouse_department']) && $queryParameter['warehouse_department']) {
			$where .= "AND " . $this->db->quoteInto(" warehouse_department =?", (int) $queryParameter['warehouse_department']) . " ";
		}

		if (isset($queryParameter['warehouse']) && $queryParameter['warehouse']) {
			$warehouseSql = "";
			foreach ($queryParameter['warehouse'] as $oneWarehouseId) {
				$oneWarehouseId = (int) $oneWarehouseId;
				if (!$oneWarehouseId) {
					continue;
				}
				$warehouseSql .= "OR " . $this->db->quoteInto(" FIND_IN_SET(?,warehouse)", $oneWarehouseId) . " ";
			}
			$warehouseSql = ltrim($warehouseSql, "OR");
			if ($warehouseSql) {
				$where .= "AND ( " . $warehouseSql . " ) ";
			}
		}

		if ($where) {
			$where = 'where ' . ltrim($where, 'AND');
		}

		$allRuleNum = $this->db->fetchOne("select count(*) as counts from b_product_backup_rule $where");
		$ruleList = [];
		$pageLink = "";

		//获取拥有仓库全部事业部名称
		$departmentModel = new Application_Model_Department();
		$warehouseDep = $departmentModel->hasWarehouse();
		$warehouseDep = array_column($warehouseDep, 'department_name', 'id');

		if ($allRuleNum) {
			$pageLink = $this->page($allRuleNum, $this->page_size);
			$queryParameter['page'] = $queryParameter['page'] ?? 1;
			$pageOffset = ($queryParameter['page'] - 1) * $this->page_size;
			$ruleList = $this->db->fetchAll($this->db->limit("select * from b_product_backup_rule $where order by create_time desc", $this->page_size, $pageOffset));

			//获取备货规则适用仓库的名称
			$warehouseModel = new Application_Model_Warehouse();
			foreach ($ruleList as &$oneBackupRule) {
				$warehouseIdArr = explode(",", $oneBackupRule['warehouse']);
				$warehouseInfo = $warehouseModel->getWarehouseById($warehouseIdArr, ['warehouse_name']);

				//规则所有适用仓库名称
				$oneBackupRule['allWarehouseName'] = "";
				//规则所有适用仓库所属部门名称
				$oneBackupRule['warehouseDepName'] = "";
				if ($warehouseInfo) {
					$oneBackupRule['warehouseDepName'] = $warehouseDep[$oneBackupRule['warehouse_department']] ?? "";
					$oneBackupRule['allWarehouseName'] = implode(",", array_column($warehouseInfo, 'warehouse_name'));
				}

			}

		}

		$this->smarty->assign('warehouseDep', $warehouseDep);
		$this->smarty->assign("queryParameter", $queryParameter);
		$this->smarty->assign('pageLink', $pageLink);
		$this->smarty->assign('ruleList', $ruleList);
		$this->smarty->display('backupRuleList.tpl');
	}

	/**
	 * 复制备货规则
	 * @return [type] [description]
	 */
	public function copyAction() {
		$copyRuleId = $this->getRequest()->getQuery('ruleId');
		if (!$copyRuleId) {
			$this->showError('请指定的备货规则id！');
		}
		$backupRuleModel = new Backup_Model_BackupRule();
		$backupRule = $backupRuleModel->getDetail($copyRuleId);
		if (!$backupRule) {
			$this->showError('未找到指定的备货规则！');
		}

		$now = date('Y-m-d H:i:s');
		unset($backupRule['id']);
		$backupRule['name'] = '复制-' . $backupRule['name'];
		$backupRule['creator'] = $this->currentLoginUser()['user_name'];
		$backupRule['modify_user'] = $this->currentLoginUser()['user_name'];
		$backupRule['create_time'] = $now;
		$backupRule['modify_time'] = $now;

		$filterRule = $backupRule['filter_rule'];
		unset($backupRule['id'], $backupRule['filter_rule']);
		foreach ($filterRule as &$oneFilterRule) {
			unset($oneFilterRule['id'], $oneFilterRule['backup_rule_id']);
		}
		if ($filterRule) {
			foreach ($filterRule as &$oneFilterRule) {
				unset($oneFilterRule['backup_rule_id']);
			}
		}

		$newBackupRuleId = $backupRuleModel->save($backupRule, $filterRule);

		if (!$newBackupRuleId) {
			$this->showError('保存备货规则数据失败！');
		}

		$this->redirect('/backup/rule/edit?ruleId=' . $newBackupRuleId);
	}
}